package com.playball.lottery.util;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.playball.lottery.ApplicationData;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * @Title: AppUtils.java
 * @Description: TODO(程序的工具类，需要帮助的都写这里)
 * @author vanszhen@gmail.com
 * @date 2013-5-28 10:30:00
 * @version V1.0
 */
public class AppUtils {


	/**
	 * 流转字符串方法
	 *
	 * @param is
	 * @return
	 */
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
		} finally {
			try {
				is.close();
			} catch (IOException e) {
			}
		}
		return sb.toString();
	}

	    private static long lastClickTime;  
	    /**
	     * 防止按钮连续点击 
	    * @Title: isFastDoubleClick 
	    * @Description: TODO(这里用一句话描述这个方法的作用) 
	    * @param @return    设定文件 
	    * @return boolean    返回类型 
	    * @throws
	     */
	    public static boolean isFastDoubleClick() {  
	        long time = System.currentTimeMillis();  
	        long timeD = time - lastClickTime;  
	        if ( 0 < timeD && timeD < 2500) {     
	            return true;     
	        }     
	        lastClickTime = time;     
	        return false;     
	    }  
	
	/**
	 * 设备的 唯一码
	* @Title: isDeviceID 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param context
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	public static String getDeviceID(Context context) {
		final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		final String tmDevice, tmSerial, tmPhone, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
		UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
		String uniqueId = deviceUuid.toString();
		return uniqueId;
	}
	
	
	 
	
	
	/**
	 * 
	* @Title: openApk 
	* @Description: TODO(安装 apk) 
	* @param @param context
	* @param @param file    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public static void openApk(Context context,File file){
		Log.e("OpenFile", file.getName());
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = getMIMEType(file);
		intent.setDataAndType(Uri.fromFile(file), type);
		context.startActivity(intent);
	}
	
	/* 判断文件MimeType */
	private static String getMIMEType(File f) {
		String type = "";
		String fName = f.getName();
		/* 取得扩展名 */
		String end = fName
				.substring(fName.lastIndexOf(".") + 1, fName.length())
				.toLowerCase();
		/* 依扩展名的类型决定MimeType */
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
				|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
				|| end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else if (end.equals("apk")) {
			/* android.permission.INSTALL_PACKAGES */
			type = "application/vnd.android.package-archive";
		} else {
			type = "*";
		}
		/* 如果无法直接打开，就跳出软件列表给用户选择 */
		if (!end.equals("apk")) {
			type += "/*";
		}

		return type;
	}
	
	/**
	 * 判断 空 null  ..
	 * @param str
	 * @return
	 */
	public static boolean isBlank(String str) {
		int strLen;

		if ((str == null) || ((strLen = str.length()) == 0)) {
			return true;
		}

		for (int i = 0; i < strLen; i++) {
			if ((Character.isWhitespace(str.charAt(i)) == false)) {
				return false;
			}
		}

		return true;
	}

	/**
	 * @Title: 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
	 * @param context
	 * @return boolean
	 * @author szw
	 */
	public static boolean checkNet(Context context) {
		try {
			ConnectivityManager cManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			if (cManager != null) {
				// 获取网络连接对象
				NetworkInfo info = cManager.getActiveNetworkInfo();
				if (info != null && info.isConnected()) {
					// 判断当前网络是否已经连接
					if (info.getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return false;
	}

	/**
	 * @Title:获取设备的唯一标示IMEI
	 * @param context
	 * @return String
	 * @author szw
	 */
	public static String getImei(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();
		return imei;
	}

	/**
	 * @Title: 判断SDCard是否存在
	 * @return
	 * @author szw
	 */
	public static boolean isExistSDCard() {
		if (android.os.Environment.getExternalStorageState().endsWith(
				android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}
	
 
	
	/**
	 * 检测SD卡剩余容量
	 * 
	 * @return
	 */
	public static int getSDCardRemainingSpace() {
		String sdcard = Environment.getExternalStorageDirectory().getPath();
		File file = new File(sdcard);
		StatFs statFs = new StatFs(file.getPath());
		int remainingSpace = (int) (statFs.getBlockSize() * ((long) statFs
				.getAvailableBlocks() - 4));
		return remainingSpace;
	}
	
	

	/**
	 * BitmapDrawable
	 * @param imgURL
	 * @return
	 */
	public static BitmapDrawable downloadBitmapDrawable(String imgURL) {
		BitmapDrawable icon = null;
		try {
			URL url = new URL(imgURL);
			HttpURLConnection hc = (HttpURLConnection) url.openConnection();
			icon = new BitmapDrawable(hc.getInputStream());
		} catch (Exception e) {
//			e.printStackTrace();
			return null;
		}
		return icon;
	}
	
	/**Bitmap
	 *  url 拿到 bitmap
	 * @param url
	 * @return
	 */
	public static Bitmap returnBitMap(String url,Context c) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		Log.d("qin", "url--------"+url);
		Resources res=c.getResources();
			try {
				myFileUrl = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) myFileUrl
						.openConnection();
				conn.setDoInput(true);
				conn.connect();
				/*String cookieval = conn.getHeaderField("set-cookie"); 
				if(cookieval != null) { 
					String sess = cookieval.substring(0, cookieval.indexOf(";")); 
					  String id[]=sess.split("=");
		              GlobalClass.SESSIONID =id[1];
		              System.out.println("服务器请求seeid"+GlobalClass.SESSIONID );
					}*/
				InputStream is = conn.getInputStream();
				bitmap = BitmapFactory.decodeStream(is);
				is.close();
			} catch (Exception e) {
//				e.printStackTrace();
			}
		return bitmap;
	}
	
	 //获得圆角图片的方法  
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx){  
          
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap  
                .getHeight(), Config.ARGB_8888);  
        Canvas canvas = new Canvas(output);  
   
        final int color = 0xff424242;  
        final Paint paint = new Paint();  
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());  
        final RectF rectF = new RectF(rect);  
   
        paint.setAntiAlias(true);  
        canvas.drawARGB(0, 0, 0, 0);  
        paint.setColor(color);  
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);  
   
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));  
        canvas.drawBitmap(bitmap, rect, rect, paint);  
   
        return output;  
    }  
	
	/**
	 * 
	 * @param urlStr
	 * @return
	 */
	public static String getSessionid(String urlStr) {
		String sess="";
		try {
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			String cookieval = conn.getHeaderField("set-cookie"); 
			if(cookieval != null) { 
				sess = cookieval.substring(0, cookieval.indexOf(";")); 
				}
		} catch (MalformedURLException e) {
//			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
		return sess;
		
	}
	/**url
	 * InputStream
	 * @param imageURL
	 * @return
	 */
	public static InputStream getStreamFromURL(String imageURL) {
		InputStream in=null;
		try {
			URL url=new URL(imageURL);
			HttpURLConnection connection=(HttpURLConnection) url.openConnection();
			in=connection.getInputStream();
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return in;
		
}
	
	/**
	 * 判断文件可存在
	 * @param fullName
	 * @return
	 */
	public static boolean isExistFile(String fullName) {
		File file = new File(fullName);
		if (file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * 删除文件
	 * @param fullName
	 */
	public static void deleteFile(String fullName) {
		File file = new File(fullName);
		if (file.exists()) {
			file.delete();
		}
	}
	
	 /**
	  * 删文件夹 下面的文件
	  * @param file
	  * 2013-7-02
	  */
	public static void deleteFile(File file) {

		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i< files.length; i++) { // 遍历目录下所有的文件
					deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
//					System.out.println("shanle");
				}
			}
			file.delete();
		} else {
//			System.out.println("---");
		}
	}

	
	/**
	 * 判断网络
	 * 所有的的网络   
	 * 是否已经连接
	 * @Title: isNetworkAvailable
	 * @Description: TODO(判断网络)
	 * @return boolean 返回类型
	 */
	public static boolean isNetworkAvailable(Context cont) {

		Context context = cont.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] infos = connectivity.getAllNetworkInfo();
			if (infos != null) {
				for (int i = 0; i < infos.length; i++) {
					if (infos[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
	 
	/**只判断wifi
	 * 
	 * @return
	 */
	public static boolean isWifiNetworkAvailable(Context cont) {

		Context context =cont.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] infos = connectivity.getAllNetworkInfo();
			if (infos != null) {
				for (int i = 0; i < infos.length; i++) {
					if (infos[i].getType()==ConnectivityManager.TYPE_WIFI&&infos[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
	

 
	
	
	/*
	 * ***************************************时间的处理********************************************************
	 */
	public static String getDateStringFromDate(Date date) {
		SimpleDateFormat formatter;
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				java.util.Locale.CHINA);
		String dateString = formatter.format(date);
		return dateString.trim();
	}

	public static Date getDateFromDateString(String dateStr) {
		SimpleDateFormat formatter;
		Date date = null;
		formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
				java.util.Locale.CHINA);
		try {
			date = (Date) formatter.parse(dateStr);
			return date;
		} catch (ParseException e) {
//			e.printStackTrace();
		}
		return null;
	}
	
	public static String getDateFromDatelong(long dateStr) {
		String time;
		SimpleDateFormat   sdf   =   new   SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
		try {
			time=sdf.format(new Date(dateStr)).toString();
			return time;
		} catch (Exception e) {
//			e.printStackTrace();
		}
		return null;
	}

	// "yyyy-MM-dd HH:mm"
	public static Date getDateFromDateStringWithoutss(String dateStr,
			String template) {
		SimpleDateFormat formatter;
		Date date = null;
		formatter = new SimpleDateFormat(template, java.util.Locale.CHINA);
		try {
			date = (Date) formatter.parse(dateStr);
		} catch (ParseException e) {
//			e.printStackTrace();
		}
		return date;
	}

	/**********************************/
	// 按个数随机取球
	
		public static int[] RandomGenData(int min, int max, int num, String color) {
			int[] temp;
			Random rndNumber;
			rndNumber = new Random();
			temp = new int[num];
			ArrayList<Integer> a1 = new ArrayList<Integer>();

			for (int i = min; i <= max; i++) {
				a1.add(i);

			}
			for (int i = 0; i < num; i++) {
				int index = rndNumber.nextInt(max - min + 1 - i);
				Object o = a1.get(index);
				temp[i] = ((Integer) o).intValue();
				/*if (color.equals("red"))
					BallRandom(0, 1, 0, temp[i]);
				if (color.equals("blue"))
					BallRandom(1, 0, 0, temp[i]);*/
				a1.remove(index);
			}
			Arrays.sort(temp);
			return temp;
		}
		/**判断登录没*/
		public static boolean checkUserLogin() {
			if (!ApplicationData.getInstance().getLoginName().equals("") && !ApplicationData.getInstance().getLoginPwd().equals("") || !ApplicationData.getInstance().getUserID().equals("")) {
				return true;
			} else {
				return false;
			}
		}
		
		
		
		/*******************dilog*********************/
		
		/**
		 * 
		 * @param cmdId
		 * @return
		 * 	1       主站
		 *	2       金山
		 *	3       联通wap
		 *	4       搜狐wap
		 *	5       主站安卓
		 *	6       主站苹果
		 *	7       无线城市安卓
		 */
		public static int getplatformTypeByCmdId(int cmdId) {
			int res = 5;
			switch (cmdId) {
			case 1034845:
			case 1181813:
				res = 7;
				break;
			}
			return res;
		}
		
		/**
		 * 检测是否连接wifi
		 * @param context
		 * @return
		 */
		public static boolean isWifiConnected(Context context){
			ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if(wifiNetworkInfo.isConnected()){
				return true ;
			}
			return false ;
		}
		
		
		
		
		/******************2014年7月4日13:46:45************************/
		public static boolean isCard(String idNum)
        {
			
			boolean flag = false ;
			 Pattern idNumPattern = Pattern.compile("(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])");  
	            //通过Pattern获得Matcher  
	            Matcher idNumMatcher = idNumPattern.matcher(idNum);  
	            //判断用户输入是否为身份证号  
	            if(idNumMatcher.matches()){  
	                System.out.println("您的出生年月日是：");  
	                //如果是，定义正则表达式提取出身份证中的出生日期  
	                Pattern birthDatePattern= Pattern.compile("\\d{6}(\\d{4})(\\d{2})(\\d{2}).*");//身份证上的前6位以及出生年月日  
	                //通过Pattern获得Matcher  
	                Matcher birthDateMather= birthDatePattern.matcher(idNum);  
	                //通过Matcher获得用户的出生年月日  
	                if(birthDateMather.find()){  
	                    String year = birthDateMather.group(1);  
	                    String month = birthDateMather.group(2);  
	                    String date = birthDateMather.group(3);  
	                    //输出用户的出生年月日  
	                    System.out.println(year+"年"+month+"月"+date+"日");                  
	                } 
	                flag = true ;
	            }else{  
	                //如果不是，输出信息提示用户  
	                System.out.println("您输入的并不是身份证号");  
	            	flag = false;
	            }
			 
	            return flag ;
			 
        }
		
		//身份证验证
		public static boolean regSFZ(String sfzhm) {
			boolean flag = false;
			//18
			//^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$
			//15
			//^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$
			Pattern patternSfzhm1 = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
			Pattern patternSfzhm2 = Pattern.compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$");
			Matcher matcherSfzhm1 = patternSfzhm1.matcher(sfzhm);
			Matcher matcherSfzhm2 = patternSfzhm2.matcher(sfzhm);
			
			if (  !matcherSfzhm1.find() && !matcherSfzhm2.find()) { 
				//showToast("身份证号码格式不正确，请重新输入！"); 
				flag = false; 
	        }  else {
				flag = true ;
			}
			
			return flag;
		}
		
		/**
		 * 世界杯投注截止
		 * @return
		 */
		public static boolean isWorldCupDeadline() {
//			boolean flag = false;
//			try {
//				Date now = new Date();
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
//				Date deadline = sdf.parse("2014-07-14 02:55");
//				flag = deadline.before(now);
//			} catch (ParseException e1) {
//				e1.printStackTrace();
//			}
//			return flag;
			return true;
		}
		
		/**
		 * 世界杯最后一场比赛
		 * @return
		 */
//		public static boolean isWorldCupLastMatch() {
//			boolean flag = false;
//			try {
//				Date now = new Date();
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
//				Date deadline = sdf.parse("2014-07-13 03:55");
//				flag = deadline.before(now);
//			} catch (ParseException e1) {
//				e1.printStackTrace();
//			}
//			return flag;
//		}
		
}
